package top.hymsk.ecommerce.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.hymsk.ecommerce.pojo.response.GeneralResponse;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
@Aspect
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    @Around("@annotation(top.hymsk.ecommerce.anno.Log)")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        long begin = System.currentTimeMillis();
        //获取请求方法和请求路径
        String method = request.getMethod();
        String path = request.getServletPath();
        //获取请求方法
//        String methodName = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        //请求方法参数
        Object args = request.getParameterMap();
        String methodPara = JSONObject.toJSONString(args);
        //执行原目标方法
        Object result = joinPoint.proceed();
        //获取方法返回值
//        String returnValue = JSON.toJSONString(result);
        GeneralResponse returnValue=JSON.parseObject(JSON.toJSONString(result),GeneralResponse.class);

        //获取相应状态
        int status = response.getStatus();
        //日志记录
//        log.info(String.format("[%s](%d) %s : %s (cost:%.3f)", method, status, path, methodPara, (System.currentTimeMillis() - begin) / 1000.0));
        log.info(String.format("[%s](%d) %s : %s -> %s (cost:%.3f)", method, status, path, methodPara, returnValue.getMsg(), (System.currentTimeMillis() - begin) / 1000.0));
//        log.info(String.format("[%s](%d) %s %s() : %s->%s (cost:%.3f)", method, status, path, methodName, methodPara, returnValue, (System.currentTimeMillis() - begin) / 1000.0));
        return result;
    }
}
